package day12.homework.project4;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Employees{
    public static List<Employee> queryAll() {
        List<Employee> employees = new ArrayList<>();
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            Document document = reader.read(new File("src\\main\\resources\\employees.xml"));
            // 通过document对象获取根节点bookstore
            Element bookStore = document.getRootElement();
//            List<Element> els = bookStore.elements("student");
            // 通过element对象的elementIterator方法获取迭代器
            Iterator it = bookStore.elementIterator();
            // 遍历迭代器，获取根节点中的信息（书籍）
            while (it.hasNext()) {
                Employee employee = new Employee();

                Element Employee = (Element) it.next();

                employee.setId(Integer.parseInt(Employee.attributeValue("id")));
                employee.setName(Employee.elementText("name"));
                employee.setSex(Employee.elementText("sex"));
                employee.setAge(Integer.parseInt(Employee.elementText("age")));
                employee.setAddress(Employee.elementText("address"));
                employees.add(employee);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return employees;
    }

    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees = queryAll();
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}
